#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
int   CountReceiveData=0;//串口接收到的光子数
int   Temp_Value1=0;//临时数据1
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    Serial_Init();
    ChartInit();
}

Widget::~Widget()
{
    delete ui;
}

void Widget::Serial_Init(){
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())  //查找可用串口
    {
        QSerialPort myserial;                   //定义串口类对象
        myserial.setPort(info);                 //设置串口端口
        if(myserial.open(QIODevice::ReadWrite)) //可读可写方式打开串口
        {
            ui->comboBox_name->addItem(myserial.portName()); //添加串口号名字 并显示到comboBox
            myserial.close();
        }
    }
    ui->comboBox_baud->setCurrentText("115200"); //设置默认波特率为115200
    //ui->DataBits_Box->setCurrentText("8");      //设置默认数据位为8位
    //ui->ChackDigit_Box->setCurrentText("None"); //设置默认无校验位
    //ui->StopBit_Box->setCurrentText("1");       //设置默认停止位为1位
    ui->Button_operate->setText("打开串口");
}

void Widget::ChartInit(){
    mline1 = new QLineSeries ();                 //构建曲线序列
    mChart = new QChart();                      //构建图表
    mChart->addSeries(mline1);                   //将曲线添加到图表
    mChart->legend()->hide();                   //隐藏图例
    QPen PenColor(Qt::red);
    PenColor.setWidth(3);
    mline1->setPen(PenColor);

    axisX = new QValueAxis();
    axisX->setRange(0, 1000);                    //设置范围
    axisX->setLabelFormat("%u");                //设置刻度的格式
    axisX->setGridLineVisible(true);            //网格线可见
    axisX->setTickCount(11);                    //设置多少个大格
    axisX->setMinorTickCount(1);                //设置每个大格里面小刻度线的数目
    //axisX->setTitleText("X");                 //设置描述

    axisY = new QValueAxis();
    axisY->setRange(0,1000);
    axisY->setLabelFormat("%u");
    axisY->setGridLineVisible(true);
    axisY->setTickCount(11);
    axisY->setMinorTickCount(1);
    //axisY->setTitleText("Y");
    mChart->addAxis(axisX, Qt::AlignBottom); //下：Qt::AlignBottom  上：Qt::AlignTop
    mChart->addAxis(axisY, Qt::AlignLeft);   //左：Qt::AlignLeft    右：Qt::AlignRight
    mline1->attachAxis(axisX);
    mline1->attachAxis(axisY);

    ui->widget->setChart(mChart);
}


void Widget::on_Button_operate_clicked()
{
    QString str=ui->Button_operate->text();
    if("打开串口"==str){
        if(ui->comboBox_name->currentText()==NULL) QMessageBox::about(this,tr("提示"),tr("串口不可用！"));
        else {
            ui->comboBox_baud->setEnabled(false);
            //ui->DataBits_Box->setEnabled(false);
            //ui->ChackDigit_Box->setEnabled(false);
            //ui->StopBit_Box->setEnabled(false);
            ui->Button_operate->setText("关闭串口");
            ui->comboBox_name->setEnabled(false);

            serial = new QSerialPort;
            serial->setPortName(ui->comboBox_name->currentText());
            serial->open(QIODevice::ReadWrite);
            switch(ui->comboBox_baud->currentText().toInt())
            {
                case 9600  : serial->setBaudRate(QSerialPort::Baud9600);break;
                case 19200 : serial->setBaudRate(QSerialPort::Baud19200);break;
                case 115200: serial->setBaudRate(QSerialPort::Baud115200);break;
            }

            serial->setDataBits(QSerialPort::Data8);
            serial->setStopBits(QSerialPort::OneStop);
            serial->setParity(QSerialPort::NoParity);
            serial->setFlowControl(QSerialPort::NoFlowControl);
            connect(serial,SIGNAL(readyRead()),this,SLOT(Read_Data()));
            //Cachefile.open(QIODevice::WriteOnly|QIODevice::Append);
        }
    }else{
        ui->Button_operate->setText("打开串口");
        ui->comboBox_baud->setEnabled(true);
        //ui->DataBits_Box->setEnabled(true);
        //ui->ChackDigit_Box->setEnabled(true);
        //ui->StopBit_Box->setEnabled(true);
        ui->comboBox_name->setEnabled(true);

        serial->clear();
        serial->close();
        serial->deleteLater();
        //Cachefile.close();
    }
}

void Widget::on_Button_Send_clicked()
{
    char DataSend[8]={0};
    if(ui->comboBox_mode->currentIndex()==0){
        DataSend[5]=0xFD;
    }else {
        DataSend[5]=0xFE;
    }
    short int CollectTime = ui->lineEdit_time->text().toUInt();
    short int CollectInterval = ui->lineEdit_interval->text().toUInt();
    //数据类型转换short int转hex
    DataSend[1]=CollectTime/250;
    DataSend[2]=CollectTime%250;
    DataSend[3]=CollectInterval/250;
    DataSend[4]=CollectInterval%250;
    //小于255时辅助发送
    for(int i=1;i<5;i++) if(DataSend[i]==0) DataSend[i]=0xFF;
    DataSend[0]=0xFB;
    DataSend[6]=0xFC;
    //发送数据
    serial->write(DataSend);
}

void Widget::on_Button_Collect_clicked()
{
    char StartCollect[7]={0};
    if(ui->Button_Collect->text() == "开始采集"){
        ui->Button_Collect->setText("停止采集");
        for(int i=1;i<5;i++)
        {
            StartCollect[i]=0xFD;
        }
    }else{
        ui->Button_Collect->setText("开始采集");
        for(int i=1;i<5;i++)
        {
            StartCollect[i]=0xFE;
        }
    }
    StartCollect[0]=0xFB;
    StartCollect[5]=0xFC;
    serial->write(StartCollect);
}

int num=0,numlast=0;
void Widget::on_Button_clear_clicked()
{
    ui->Browser_data->clear();
    ui->Browser_bebug->clear();
    mline1->clear();
    num=0;
}

void Widget::Read_Data()
{
    QByteArray buf;
    QString Show_String;
    QByteArray ba;//输出Tab空格
    ba.resize(1);
    ba[0]=0x09;
    buf=serial->readAll();
    if(buf.data()[0]=='~')
    {
     if(buf.data()[buf.length() - 1] == '!')//一次接受完成 数据包尾
     {
         for(int j=0;j<4;j++)
         {
             CountReceiveData<<=8;
             Temp_Value1=(buf.data()[1+j])&(0xff);
             CountReceiveData|=Temp_Value1;
         }
         mline1->append(num++,CountReceiveData);
         Show_String=QString::number(CountReceiveData);
         ui->Browser_data->insertPlainText(Show_String);//将接收到的数据显示出来
         ui->Browser_data->insertPlainText(ba);//输出Tab空格
     }
   }
   else
    {
        ui->Browser_bebug->insertPlainText(buf);//将接收到的数据显示出来
    }
    //ui->Browser_data->insertPlainText(buf+"\r\n");
    buf.clear();
}




